from operator import truediv
import vec
import random
import pgzrun
import time

IMG_SIZE = 160
SIZE = 3

WIDTH = IMG_SIZE * 3
HEIGHT = IMG_SIZE * 3

BACK_COLOR = (0, 0, 0)

images = {}

for i in range(1, 9):
    images[i] = Actor(str(i))

board = list(range(9))
random.shuffle(board)
print(board)

moving = False
activeImg = None
startIndex = 0
endIndex = 0
startPos = vec.Vec2(0, 0)
endPos = vec.Vec2(0, 0)
spd = 3
lastTime = time.time()
deltaTime = 0
p = 0

for r in range(SIZE):
    for c in range(SIZE):
        x = c * IMG_SIZE + IMG_SIZE // 2
        y = r * IMG_SIZE + IMG_SIZE // 2
        num = board[r * SIZE + c]
        if num > 0:
            img = images[num]
            img.pos = x, y

def GetRowColFromIndex(idx):
    r = int(idx / SIZE)
    c = int(idx % SIZE)
    return r, c

def GetIndexFromRowCol(r, c):
    return r * SIZE + c

def GetRowColFromPos(pos):
    c = pos[0] // IMG_SIZE
    r = pos[1] // IMG_SIZE
    return r, c

def FindWay(r, c):
    global board
    if r + 1 < SIZE:
        idx = GetIndexFromRowCol(r + 1, c)
        if board[idx] == 0:
            return r + 1, c

    if r - 1 >= 0:
        idx = GetIndexFromRowCol(r - 1, c)
        if board[id]x == 0:
            return r - 1, c

    if c - 1 >= 0:
        idx = GetIndexFromRowCol(r, c - 1)
        if board[idx] == 0:
            return r, c - 1

    if c + 1 < SIZE:
        idx = GetIndexFromRowCol(r, c + 1)
        if board[idx] == 0:
            return r, c + 1

    return r, c


def on_mouse_up(pos):
    global startIndex, endIndex, moving, activeImg, board, images
    global activeImg, p
    print("mouse_up", pos)
    r, c = GetRowColFromPos(pos)
    rr, cc = FindWay(r, c)

    if rr == r and cc == c:
        return

    moving = True
    startIndex = GetIndexFromRowCol(r, c)
    endIndex = GetIndexFromRowCol(rr, cc)
    num = board[startIndex]
    activeImg = images[num]
    startPos.x = c * IMG_SIZE + IMG_SIZE // 2
    startPos.y = r * IMG_SIZE + IMG_SIZE // 2
    endPos.x = cc * IMG_SIZE + IMG_SIZE // 2
    endPos.y = rr * IMG_SIZE + IMG_SIZE // 2
    p = 0
        
def moveNum(deltaTime):
    global spd, activeImg, startPos, endPos, moving
    global board, startIndex, endIndex, p

    p += spd * deltaTime

    if p < 1:
        newPos = startPos * (1 - p) + endPos * p
        activeImg.pos = newPos.x, newPos.y

    else:
        activeImg.pos = endPos.x, endPos.y
        moving = False
        board[startIndex], board[endIndex] = board[endIndex], board[startIndex]

def update():
    global deltaTime, lastTime
    
    curTime = time.time()
    deltaTime = curTime - lastTime
    lastTime = curTime

    if moving == False:
        return

    moveNum(deltaTime)

def draw():
    screen.fill(BACK_COLOR) 

    for v in images.values():
        v.draw()

pgzrun.go()